import { defineStore } from 'pinia'

import defaultSettings from '@/settings'
import { IChangeSetting } from './type/index'

const {
  sideTheme,
  showSettings,
  topNav,
  tagsView,
  fixedHeader,
  sidebarLogo,
  dynamicTitle,
} = defaultSettings

const layoutSetting = localStorage.getItem('layout-setting')
const storageSetting = layoutSetting ? JSON.parse(layoutSetting) : ''

const useSettingsStore = defineStore('settings', {
  state: () => ({
    /**
     * 网页标题
     */
    title: '',
    theme: storageSetting.theme || '#409EFF',
    /**
     * 侧边栏主题 深色主题theme-dark，浅色主题theme-light
     */
    sideTheme: storageSetting.sideTheme || defaultSettings.sideTheme,
    /**
     * 是否系统布局配置
     */
    showSettings: defaultSettings.showSettings,
    /**
     * 是否显示顶部导航
     */
    topNav:
      storageSetting.topNav === undefined
        ? defaultSettings.topNav
        : storageSetting.topNav,
    /**
     * 是否显示 tagsView
     */
    tagsView:
      storageSetting.tagsView === undefined
        ? defaultSettings.tagsView
        : storageSetting.tagsView,
    /**
     * 是否固定头部
     */
    fixedHeader:
      storageSetting.fixedHeader === undefined
        ? defaultSettings.fixedHeader
        : storageSetting.fixedHeader,
    /**
     * 是否显示logo
     */
    sidebarLogo:
      storageSetting.sidebarLogo === undefined
        ? defaultSettings.sidebarLogo
        : storageSetting.sidebarLogo,
    /**
     * 是否显示动态标题
     */
    dynamicTitle:
      storageSetting.dynamicTitle === undefined
        ? defaultSettings.dynamicTitle
        : storageSetting.dynamicTitle,
  }),
  actions: {
    /**
     * 修改布局设置
     * @param data
     */
    changeSetting(data: IChangeSetting) {
      const { key, value } = data
      if (this.hasOwnProperty(key)) {
        ;(this as any)[key] = value
      }
    },
    /**
     * 设置网页标题
     * @param title
     */
    setTitle(title: string) {
      this.title = title
      this.useDynamicTitle()
    },

    /**
     * 动态修改标题
     */
    useDynamicTitle() {
      if (this.dynamicTitle) {
        document.title = this.title + ' - ' + defaultSettings.title
      } else {
        document.title = defaultSettings.title
      }
    },
  },
})

export default useSettingsStore
